package com.example.mylibrary;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.os.RemoteException;

import com.example.aidlservice.IClientCallBack;
import com.example.aidlservice.IMyAidlInterface;
import com.example.aidlservice.User;

public class MyLib {
    private IMyAidlInterface iMyAidlInterface;
    private ConnectedListener connectedListener;

    public interface ConnectedListener {
        // 回调方法
        void LibConnected();
    }

    public void setOnConnectedListener(ConnectedListener connectedListener) {
        this.connectedListener = connectedListener;
    }

    public MyLib(Context context) {
        Intent intent = new Intent();
        intent.setPackage("com.example.aidlservice");
        intent.setAction("com.example.aidlservice.action");
        context.bindService(intent, new ServiceConnection() {

            @Override
            public void onServiceConnected(ComponentName name, IBinder service) {

                iMyAidlInterface = IMyAidlInterface.Stub.asInterface(service);
                if (connectedListener != null)
                    connectedListener.LibConnected();
            }

            @Override
            public void onServiceDisconnected(ComponentName name) {

            }
        }, Context.BIND_AUTO_CREATE);
    }

    public String getName() {
        try {
            return iMyAidlInterface.getName();
        } catch (RemoteException e) {
            e.printStackTrace();
        }
        return null;
    }

    public User getUser() {
        try {
            return iMyAidlInterface.getUser();
        } catch (RemoteException e) {
            e.printStackTrace();
        }
        return null;
    }

    public void registerCallBack(IClientCallBack cb) {
        try {
            iMyAidlInterface.register(cb);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }
}
